package com.prashantdctm.paidemail;

import java.io.BufferedReader;

import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.List;
import java.util.StringTokenizer;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.w3c.dom.Document;
import org.w3c.dom.NodeList;

import com.gargoylesoftware.htmlunit.gae.GAEUtils;
import com.gargoylesoftware.htmlunit.html.DomNode;
import com.gargoylesoftware.htmlunit.html.DomNodeList;
import com.gargoylesoftware.htmlunit.html.HtmlAnchor;
import com.gargoylesoftware.htmlunit.html.HtmlCheckBoxInput;
import com.gargoylesoftware.htmlunit.html.HtmlDivision;
import com.gargoylesoftware.htmlunit.html.HtmlElement;
import com.gargoylesoftware.htmlunit.html.HtmlForm;
import com.gargoylesoftware.htmlunit.html.HtmlImage;
import com.gargoylesoftware.htmlunit.html.HtmlImageInput;
import com.gargoylesoftware.htmlunit.html.HtmlOption;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import com.gargoylesoftware.htmlunit.html.HtmlPasswordInput;
import com.gargoylesoftware.htmlunit.html.HtmlRadioButtonInput;
import com.gargoylesoftware.htmlunit.html.HtmlSelect;
import com.gargoylesoftware.htmlunit.html.HtmlTextInput;
import com.prashantdctm.utils.EmailUtil;
import com.prashantdctm.utils.GaeUtil;
import com.prashantdctm.utils.GeneralUtil;
import com.prashantdctm.utils.HttpUtil;
import com.prashantdctm.utils.XMLUtil;

public class PaidEmailServlet extends GaeHttpServlet {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	public static boolean debugMode = false;

	public static void main(String[] args) throws Exception {
		webClient = HttpUtil.getWebClient();
		initLocalLog("C:\\Users\\prashantkumar\\logs", true);
		startProcessing("h4p", "pk_jsp", "pk_995");
		// System.exit(0);

		if (args.length == 0) {
			// directly running this program from eclipse
			runCronJob(null);
		} else if (args.length == 2) {
			// running from command line but for all sites
			debugMode = new Boolean(args[1]);
			runCronJob(args[0]);
		} else if (args.length > 2) {
			// running from command line but for specific site
			debugMode = new Boolean(args[1]);
			startProcessing(args[2], args[3], args[4]);
		}

		// startProcessing("h4p", "pk_jsp", "pk_995");
		// startProcessing("starclicks", "pk.dwarka@gmail.com", "pk_995");
		// startProcessing("inboxdollars", "amit11101979@yahoo.com", "pk_995");
		// startProcessing("inboxdollars", "pk.paidemails@gmail.com", "pk_995");
		//

		/*
		 * startInboxDollars("pk.paidemails@gmail.com", "pk_995");
		 */// startTesasTeaEmails("prashantdctm", "prashantdctm123");
			// startStarClicks("pk.dwarka@gmail.com", "pk_995");
			// startStarClicks("anika110579@gmail.com", "anika11");
			// startMatrixMails("pk.paidemails@gmail.com", "pk_995");
			// startSendEarnings("poonam.jsp@gmail.com", "pk_995");
			// startSendEarnings("anika110579@gmail.com", "rintu123");
	}

	public static void runCronJob(String appDir) throws Exception {
		Document doc = null;
		if (appDir != null) {
			doc = XMLUtil.getDOMObject(appDir + "\\war\\WEB-INF\\cron.xml");
		} else {
			doc = XMLUtil.getDOMObject(new File(".").getCanonicalPath()
					+ "\\war\\WEB-INF\\cron.xml");
		}

		NodeList nodes = XMLUtil.getXPath(doc, "//cron/url");
		for (int i = 0; i < nodes.getLength(); i++) {
			String url = nodes.item(i).getTextContent();
			// System.out.println(url);
			StringTokenizer stk = new StringTokenizer(url, "&");
			while (stk.hasMoreTokens()) {
				String site = stk.nextToken();
				site = site.substring(site.indexOf("=") + 1);
				String user = stk.nextToken();
				user = user.substring(user.indexOf("=") + 1);
				String pwd = stk.nextToken();
				pwd = pwd.substring(pwd.indexOf("=") + 1);
				resetVariables();
				customLog("###################################################");

				startProcessing(site, user, pwd);
			}

		}

	}

	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		super.doGet(req, resp);

		if (!isCron) {
			return;
		}

		String site = req.getParameter("site");
		String user = req.getParameter("user");
		String pwd = req.getParameter("pwd");

		startProcessing(site, user, pwd);

		try {
			if (site.equals("onepercent")
					&& user.equals("anika110579@gmail.com")) {
				resetMessageLog();

				if (GAEUtils.isGaeMode()) {
					EmailUtil.sendEmail(messageLog.toString(), "GAE Report");
				}
			}
		} catch (Exception e) {
			customException("", e);
		}
	}

	private static void startProcessing(String site, String user, String pwd) {
		if (site != null && user != null && pwd != null) {
			resetVariables();
			customLog("Logging in " + site + " as " + user);
			try {
				if (site.equals("inboxdollars")) {
					startInboxDollars(user, pwd);
				} else if (site.equals("sendearnings")) {
					startSendEarnings(user, pwd);
				} else if (site.equals("matrixmails")) {
					startMatrixMails(user, pwd);
				} else if (site.equals("onepercent")) {
					startOnePercent(user, pwd);
				} else if (site.equals("mistyandsams")) {
					startMistyAndSams(user, pwd);
				} else if (site.equals("silvestermails")) {
					startSilvesterMails(user, pwd);
				} else if (site.equals("starclicks")) {
					startStarClicks(user, pwd);
				} else if (site.equals("h4p")) {
					startH4p(user, pwd);
				}
			} catch (Exception e) {
				customException("", e);
			}

			customLog("Total messages read: " + messagesRead);
			customLog("Previous Earning: " + earningBefore);
			customLog("Current Earning: " + earningAfter);

			webClient.closeAllWindows();
			stopWatch.stop();
			customLog("Time taken: " + stopWatch.toString());
		}
	}

	public static void sendGAEReport() {
		GaeUtil.sendReport();
	}

	public static void startH4p(String username, String pwd) throws Exception {
		HtmlPage page = null;
		try {
			page = webClient
					.getPage("http://hits4pay2.com/members/loginreadmail.cgi?pk_jsp");
			for (HtmlForm form : page.getForms()) {
				if (form.getActionAttribute().startsWith(
						"http://hits4pay.com/cgi-bin/password.cgi")) {
					form.getInputByName("USERNAME").setValueAttribute(username);
					form.getInputByName("PASSWORD").setValueAttribute(pwd);
					page = form.getInputByValue("Click Here To Log In").click();
					// GeneralUtil.dumpPage(page);

					break;
				}
			}
		} catch (Exception e) {
			customException("Error in logging ", e);
			return;
		}

		// go to home page
		// page = HttpUtil.getAnchorStartsWith(page,
		// "http://hits4pay2.com/members_only/index.shtml").click();

		// GeneralUtil.dumpPage(page);
		earningBefore = checkH4pEarnings(page);
		customLog("Checking current earning: " + earningBefore);
		// GeneralUtil.dumpPage(page);

		while (true) {
			page = HttpUtil.getAnchorStartsWith(page,
					"http://hits4pay2.com/cgi-bin/viewmail.cgi").click();

			// only for reading missed messages
			/*
			 * for(HtmlAnchor anchor : page.getAnchors()) {
			 * if(anchor.getHrefAttribute().contains("ViewMailRead")){ page =
			 * anchor.click(); } }
			 */

			// look for paid link
			// GeneralUtil.dumpPage(page);
			HtmlAnchor anchor = HttpUtil.getAnchorContains(page, "&Credited&");

			// if no message return
			if (anchor == null) {
				customLog("No message to read...");
				break;
			}

			// Read message
			messagesRead++;
			customLog("Clicking message " + messagesRead);
			HtmlPage advPage = anchor.click();
			// GeneralUtil.dumpPage(advPage);

			HtmlElement topFrameElement = (HtmlElement) advPage.getByXPath(
					"//frameset/frame[@name='validation']").get(0);
			// customLog(topFrameElement.getAttribute("src"));
			HtmlPage topFramePage = webClient.getPage(topFrameElement
					.getAttribute("src"));
			customLog(topFramePage.asText());
			Thread.sleep(85000);
			HtmlElement metaElement = (HtmlElement) topFramePage.getByXPath(
					"//meta[@http-equiv='refresh']").get(0);
			String tmpStr = metaElement.getAttribute("content");
			// customLog(tmpStr.substring(tmpStr.indexOf("url=")+4));
			customLog(webClient.getPage(
					tmpStr.substring(tmpStr.indexOf("url=") + 4)).asText());

			// now delete the message
			customLog("Deleting message ");
			HttpUtil.getAnchorContains(page, "Delete").click();

		}

		earningAfter = checkH4pEarnings(page);
	}

	public static String checkH4pEarnings(HtmlPage page) throws IOException {
		// HtmlPage tmpPage = HttpUtil.getAnchorStartsWith(page,
		// "http://hits4pay2.com/members_only/index.shtml").click();

		List<HtmlElement> nodes = (List<HtmlElement>) page
				.getByXPath("//font[@color='#99CC00']");
		for (HtmlElement element : nodes) {
			if (element.getTextContent().startsWith("Total Current Balance")) {
				return element.getTextContent();
			}
		}
		return null;
	}

	public static void startStarClicks(String username, String pwd)
			throws Exception {
		HtmlPage page = null;
		try {
			page = webClient.getPage("https://www.star-clicks.com/login.asp");
			((HtmlTextInput) page.getElementByName("email"))
					.setValueAttribute(username);
			((HtmlPasswordInput) page.getElementByName("Password"))
					.setValueAttribute(pwd);
			HtmlSelect type = (HtmlSelect) page.getElementByName("type");
			List<HtmlOption> options = type.getOptions();
			for (HtmlOption option : options) {
				if (option.getText().contains("I am a Publisher")) {
					type.setSelectedAttribute(option, true);
					break;
				}
			}
			HtmlElement loginElement = page.getElementById("loginButton");
			page = loginElement.click();
		} catch (Exception e) {
			customException("Error in logging ", e);
			return;
		}

		earningBefore = checkStarClicksEarnings();
		customLog("Checking current earning: " + earningBefore);

		/*
		 * page =
		 * webClient.getPage("https://www.star-clicks.com/secure/links.asp");
		 * boolean moreMessages = true; while(moreMessages == true) {
		 * for(HtmlAnchor anchor : page.getAnchors()) {
		 * if(anchor.getHrefAttribute
		 * ().startsWith("https://www.star-clicks.com/secure/links.asp")) {
		 * messagesRead++;
		 * customLog("Clicking message "+messagesRead+": "+anchor
		 * .getTextContent()); anchor.click(); Thread.sleep(3000); } } }
		 */

		// while ads present, click
		while (true) {
			page = webClient
					.getPage("https://www.star-clicks.com/secure/links.aspx");
			// GeneralUtil.dumpPage(page);

			HtmlDivision div = (HtmlDivision) page.getByXPath(
					"//div[@title='Click to get paid']").get(0);
			if (div != null) {
				messagesRead++;
				div.click();
				Thread.sleep(1000);
			} else {
				customLog("No message to click! ");
				break;
			}
		}

		earningAfter = checkStarClicksEarnings();
		webClient.getPage("https://www.star-clicks.com/secure/logout.asp");
	}

	public static String checkStarClicksEarnings() throws Exception {
		String earnings = "";
		HtmlPage page = webClient.getPage("https://www.star-clicks.com");

		try {
			earnings = ((HtmlElement) page.getByXPath(
					"//dl[@id='accountinfo']/dt/span").get(0)).getTextContent();
		} catch (Exception e) {
			customException("Error checking earnings", e);
		}
		return earnings;
	}

	public static void startTesasTeaEmails(String username, String pwd)
			throws Exception {
		HtmlPage page = null;
		page = webClient.getPage("http://tesasteamails.com/pages/enter.php");

		((HtmlTextInput) page.getElementByName("username"))
				.setValueAttribute(username);
		((HtmlPasswordInput) page.getElementByName("password"))
				.setValueAttribute(pwd);
		page = page.getElementByName("submit").click();

		earningBefore = checkTesasTeaEmails(page);
		customLog("Checking current earning: " + earningBefore);

		// while (messagesRead < 2) {
		page = webClient.getPage("http://tesasteamails.com/pages/ptc.php");
		// GeneralUtil.dumpPage(page);
		// check if message exists
		List<HtmlAnchor> anchors = page.getAnchors();
		for (HtmlAnchor anchor : anchors) {
			// System.out.println(anchor.getHrefAttribute());.getParent().getParent().getParent().getNextSibling().getTextContent()
			if (anchor.getHrefAttribute().startsWith(
					"http://tesasteamails.com/scripts/runner.php?PA")) {
				messagesRead++;
				// String subject =
				// anchor.getParentNode().getParentNode().getParentNode().getNextSibling().getTextContent();
				// customLog("SUBJECT "+subject);
				// System.exit(0);
				String tmpStr = anchor.getAttribute("onclick");
				int refreshTime = Integer.parseInt(tmpStr.substring(
						tmpStr.indexOf("(") + 1, tmpStr.lastIndexOf(")")));
				customLog("Refresh Time " + refreshTime);
				// boolean messageSuccessfullyRead = false;
				for (DomNode element : anchor.getChildElements()) {
					if (element.getNodeName().equalsIgnoreCase("img")) {
						customLog(element.getNodeName());
						customLog("Clicking message: "
								+ anchor.getHrefAttribute());
						HtmlPage advPage = anchor.click();
						// GeneralUtil.dumpPage(advPage);
						try {
							HtmlForm botForm = advPage
									.getFormByName("botdetect");
							customLog("Question: "
									+ botForm.getPreviousSibling()
											.getPreviousSibling()
											.getTextContent());
							for (HtmlElement botElement : botForm
									.getChildElements()) {
								customLog("Option: "
										+ botElement.asXml().trim());
							}
							BufferedReader br = new BufferedReader(
									new InputStreamReader(System.in));
							customLog("Setting " + br.readLine().trim());
							HtmlRadioButtonInput input = (HtmlRadioButtonInput) botForm
									.getInputByValue(br.readLine().trim());
							input.click();
							advPage = botForm.getInputByName("submit").click();
							// GeneralUtil.dumpPage(advPage);
							// while more adv on this top frame, click and wait
							// for reqiored time
							// customLog("Top Frame "+advPage.getByXPath("//frame[@name='timerfrm']").get(0));
							HtmlElement topFrameElement = (HtmlElement) advPage
									.getByXPath("//frame[@name='timerfrm']")
									.get(0);
							String url = topFrameElement.getAttribute("src");

							clickAdv(url, 30000);

						} catch (Exception ee) {
							// Bot form not found
							// customLog("Bot Form not found");
							// while more adv on this top frame, click and wait
							// for reqiored time
							// customLog("Top Frame "+advPage.getByXPath("//frame[@name='timerfrm']").get(0));
							HtmlElement topFrameElement = (HtmlElement) advPage
									.getByXPath("//frame[@name='timerfrm']")
									.get(0);
							String url = topFrameElement.getAttribute("src");

							clickAdv(url, 30000);
						}

					}
					System.exit(0);
				}

			}

		}

		// }
	}

	public static void clickAdv(String url, int interval) throws Exception {
		customLog("Clicking on url: " + url);
		HtmlPage page = webClient.getPage(url);
		// GeneralUtil.dumpPage(page);
		Thread.sleep(interval + 2);
		// look for adv link
		for (HtmlAnchor anchor : page.getAnchors()) {
			// System.out.println(anchor.getHrefAttribute());
			if (anchor.getHrefAttribute().startsWith(
					"http://tesasteamails.com/scripts/runner.php?PA")) {
				messagesRead++;
				String subject = "";
				String tmpStr = anchor.getAttribute("onclick");
				int refreshTime = Integer.parseInt(tmpStr.substring(
						tmpStr.indexOf("(") + 1, tmpStr.lastIndexOf(")")));
				customLog("Refresh Time " + refreshTime);
				clickAdv(anchor.getHrefAttribute(), refreshTime);
			}
		}
	}

	public static String checkTesasTeaEmails(HtmlPage page) throws Exception {
		List<HtmlElement> nodes = (List<HtmlElement>) page
				.getByXPath("//strong[text()='Your account balance after all transactions:']");
		if (nodes.size() > 0) {
			return nodes.get(0).getTextContent();
		}
		return null;
	}

	public static void startMistyAndSams(String username, String pwd)
			throws Exception {
		HtmlPage page = null;
		page = webClient
				.getPage("http://www.mistyandsamscash.com/pages/enter.php");
		webClient.waitForBackgroundJavaScript(5000);

		for (HtmlForm form : page.getForms()) {
			if (form.getAttribute("method").equals("post")) {
				form.getInputByName("username").setValueAttribute(username);
				form.getInputByName("password").setValueAttribute(pwd);
				page = form.getInputByName("submit").click();
				break;
			}
		}

		// earningBefore = checkMistyAndSams();
		customLog("Checking current earning: " + earningBefore);

		while (messagesRead < 2) {
			page = webClient
					.getPage("http://www.mistyandsamscash.com/pages/inbox2.php");
			// GeneralUtil.dumpPage(page);
			// check if message exists
			List<HtmlAnchor> anchors = page.getAnchors();
			for (HtmlAnchor anchor : anchors) {
				System.out.println(anchor.getHrefAttribute());
				if (anchor
						.getHrefAttribute()
						.startsWith(
								"http://www.mistyandsamscash.com/scripts/runner.php?IM=")) {
					messagesRead++;
					boolean messageSuccessfullyRead = false;
					String messageId = anchor.getHrefAttribute().substring(
							anchor.getHrefAttribute().indexOf("IM="));
					String subject = anchor.getFirstChild().getTextContent();
					String date = anchor.getParentNode().getParentNode()
							.getPreviousSibling().getFirstChild()
							.getTextContent();
					customLog("MessageId: " + messageId + " | Subject: "
							+ subject + " | Date: " + date);

				}
			}
		}
	}

	public static String checkMistyAndSams() throws Exception {
		HtmlPage page = webClient
				.getPage("http://www.mistyandsamscash.com/pages/enter.php");
		List<HtmlElement> nodes = (List<HtmlElement>) page
				.getByXPath("//tr/td/font/b/font");
		for (HtmlElement element : nodes) {
			if (element.getTextContent().contains(
					"Your account balance after all transactions")) {
				return element.getParentNode().getParentNode().getParentNode()
						.getNextSibling().getFirstChild().getFirstChild()
						.getFirstChild().getTextContent();
			}
		}
		return null;
	}

	public static void startOnePercent(String username, String pwd)
			throws Exception {
		HtmlPage page = null;

		try {
			// Get the first page (login), fill form and submit
			page = webClient
					.getPage("http://tokes.1percent.com/main.phtml?page=rewards_home&");
			HtmlForm form = page.getFormByName("form");

			form.getInputByName("login_user_id").setValueAttribute(username);
			form.getInputByName("login_password").setValueAttribute(pwd);
			page = (HtmlPage) form.getInputByValue("Submit").click();
			// dumpPage(page);
			webClient.waitForBackgroundJavaScript(5000);

			HtmlAnchor anchor = page
					.getAnchorByHref("/main.phtml?page=site_activities&");
			page = anchor.click();
			// dumpPage(page);

			earningBefore = checkOnePercent(page);
			customLog("Current Balance:");
			customLog("Total Tokes - " + earningBefore);

			List<HtmlAnchor> anchors = page.getAnchors();
			for (HtmlAnchor anchor1 : anchors) {
				if (anchor1.getHrefAttribute().contains("action=web_links&")) {
					messagesRead++;
					customLog("Clicking toke task "
							+ anchor1.getFirstChild().getTextContent());
					anchor1.click();
				}
			}
			// Log off
			webClient
					.getPage("http://tokes.1percent.com/main.phtml?action=logout&");
		} catch (Exception e) {
			customException("Exception in checking messages ", e);
			e.printStackTrace();
		}

	}

	public static String checkOnePercent(HtmlPage page) throws Exception {
		List<HtmlElement> elements = (List<HtmlElement>) page
				.getByXPath("//img[@alt = 'Total Tokes']");
		for (HtmlElement element : elements) {
			String earning = element.getParentNode().getParentNode()
					.getNextSibling().getFirstChild().getFirstChild()
					.getTextContent();
			return earning;
		}
		return null;
	}

	public static void startSilvesterMails(String username, String pwd)
			throws Exception {
		HtmlPage page = null;
		page = webClient.getPage("http://silvester-mails.com/pages/enter.php");
		try {
			for (HtmlForm form : page.getForms()) {
				form.getInputByName("username").setValueAttribute(username);
				form.getInputByName("password").setValueAttribute(pwd);
				page = form.getInputByValue("Login").click();
				break;
			}
		} catch (Exception e) {
			customException("Error in logging ", e);
			e.printStackTrace();
			return;
		}
		// GeneralUtil.dumpPage(page);

		page = webClient.getPage("http://silvester-mails.com/pages/ptc.php");
		webClient.waitForBackgroundJavaScript(5000);

		List<HtmlAnchor> anchors = page.getAnchors();
		for (HtmlAnchor anchor : anchors) {
			// System.out.println(anchor.getHrefAttribute());
			if (anchor.getHrefAttribute().startsWith(
					"http://silvester-mails.com/scripts/runner.php?PA=")) {
				System.out.println(anchor.getHrefAttribute());
				messagesRead++;
				anchor.click();
				Thread.sleep(1000);
			}
		}
	}

	public static void startClixSense(String username, String pwd)
			throws Exception {
		HtmlPage page = null;
		try {
			page = webClient.getPage("http://www.clixsense.com");
			for (HtmlForm form : page.getForms()) {
				if (form.getAttribute("action").equals(
						"https://www.clixsense.com/en/Sign_In")) {
					form.getInputByName("username").setValueAttribute(username);
					form.getInputByName("password").setValueAttribute(pwd);
					page = form.getInputByValue("Sign In").click();
					break;
				}
			}
		} catch (Exception e) {
			customException("Error in logging ", e);
			e.printStackTrace();
			return;
		}

		page = webClient.getPage("http://www.clixsense.com/en/View_Ads");
		webClient.waitForBackgroundJavaScript(5000);

		// earningBefore = checkInboxDollars();
		customLog("Checking current earning: " + earningBefore);
		// GeneralUtil.dumpPage(page);

		StringBuffer advUrl = new StringBuffer(
				"http://www.clixsense.com/en/View_Ads/");
		for (HtmlElement element : (List<HtmlElement>) page
				.getByXPath("//table")) {
			if (element.getAttribute("onclick").startsWith("adOpen")) {
				messagesRead++;

				StringTokenizer stk = new StringTokenizer(
						element.getAttribute("onclick"), ",");
				// adOpen(this,1,167980,'069533');
				stk.nextToken();
				stk.nextToken();
				advUrl.append(stk.nextToken());
				String tmpStr = stk.nextToken();
				advUrl.append("/"
						+ tmpStr.substring(tmpStr.indexOf("'") + 1,
								tmpStr.lastIndexOf("'")));

				String subject = element.getFirstChild().getFirstChild()
						.getFirstChild().getFirstChild().getTextContent();
				customLog("Subject: " + subject);

				HtmlPage advPage = webClient.getPage(advUrl.toString());
				// GeneralUtil.dumpPage(advPage);
			}
		}

	}

	public static void startMatrixMails(String username, String pwd)
			throws Exception {
		HtmlPage page = null;

		try {
			page = webClient.getPage("http://www.matrixmails.com/?p=enter");
			webClient.waitForBackgroundJavaScript(5000);
			HtmlForm form = page.getFormByName("frmLogin");
			form.getInputByName("email").setValueAttribute(username);
			form.getInputByName("pwd").setValueAttribute(pwd);
			page = form.getInputByValue(" Enter ").click();
		} catch (Exception e) {
			customException("Error in logging ", e);
			e.printStackTrace();
			return;
		}

		earningBefore = checkMatrixMails(page);
		customLog("Checking current earning: " + earningBefore);

		// go to paid email page
		for (HtmlAnchor anchor : page.getAnchors()) {
			if (anchor.getHrefAttribute().contains("t=paidlinks")) {
				page = anchor.click();
				break;
			}
		}
		// GeneralUtil.dumpPage(page);

		customLog("Landed into inbox page, processing messages");
		// customLog(page.asXml());

		for (HtmlAnchor anchor : page.getAnchors()) {
			// check if message exists
			if (anchor.getHrefAttribute().contains(
					"http://www.matrixmails.com/?p=pct")) {
				messagesRead++;
				customLog("Reading message: " + messagesRead);
				HtmlPage advPage = anchor.click();
				// GeneralUtil.dumpPage(advPage);
				// customLog("Top Frame "+advPage.getByXPath("//frameset/frame[@name='track']").get(0));
				HtmlElement topFrameElement = (HtmlElement) advPage.getByXPath(
						"//frameset/frame[@name='track']").get(0);
				customLog(topFrameElement.getAttribute("src"));
				HtmlPage topFramePage = webClient.getPage(topFrameElement
						.getAttribute("src"));
				// GeneralUtil.dumpPage(topFramePage);
				Thread.sleep(30000); // frame

				List<HtmlImage> images = (List<HtmlImage>) topFramePage
						.getByXPath("//img");
				for (HtmlImage img : images) {
					if (img.getAttribute("src")
							.equals("http://www.matrixmails.com/images/timer/buttona.gif")) {
						// customLog("Clicking image "+img.getAttribute("src"));
						img.click();
					}
				}
			}

		}
		earningAfter = checkMatrixMails(page);

		// page = HtmlUtil.getAnchorStartsWith(page, "/members/logout").click();

		customLog("Logging out: " + username);
		webClient.getPage("http://www.inboxdollars.com/members/logout/true");

	}

	public static String checkMatrixMails(HtmlPage page) throws Exception {
		HtmlPage tmpPage = null;
		try {
			for (HtmlAnchor anchor : page.getAnchors()) {
				if (anchor.getHrefAttribute().contains("t=stats")) {
					tmpPage = anchor.click();
					break;
				}
			}

			List<HtmlElement> nodes = (List<HtmlElement>) tmpPage
					.getByXPath("//tr/td/strong/font");
			for (HtmlElement element : nodes) {
				if (element.getTextContent().contains("Total Balance:")) {
					return element.getParentNode().getParentNode()
							.getNextSibling().getNextSibling().getFirstChild()
							.getFirstChild().getTextContent();
				}
			}
		} catch (Exception e) {
			// e.printStackTrace();
		}

		return null;
	}

	public static void startInboxDollars(String username, String pwd)
			throws Exception {
		HtmlPage page = null;
		HtmlPage advPage = null;
		try {
			page = webClient.getPage("http://www.inboxdollars.com");
			webClient.waitForBackgroundJavaScript(5000);

			for (HtmlForm form : page.getForms()) {
				if (form.getAttribute("action").equals("/members/login")) {
					form.getInputByName("data[Member][username]")
							.setValueAttribute(username);
					form.getInputByName("data[Member][password]")
							.setValueAttribute(pwd);
					try {
						HtmlImageInput imgInput = form.getInputByName("submit");
						page = (HtmlPage) imgInput.click();
					} catch (Exception tempException) {

					}
					try {
						HtmlImageInput imgInput = form
								.getInputByName("submit2");
						page = (HtmlPage) imgInput.click();
					} catch (Exception tempException) {

					}
					break;
				}
			}
		} catch (Exception e) {
			customException("Error in logging ", e);
			e.printStackTrace();
			return;
		}

		// customLog(page.asXml());
		earningBefore = checkInboxDollars();
		customLog("Checking current earning: " + earningBefore);

		customLog("Landed into inbox page, processing messages");
		HtmlAnchor anchor = null;

		while (messagesRead < 100) { // no more than this no of messages to read
										// in this session, also acts as
										// recursive loop
			page = webClient.getPage("http://www.inboxdollars.com/mailbox");
			// check if message exists
			if ((anchor = HttpUtil.getAnchorContains(page, "members/email/")) == null) {
				// no adv messages found, look for 'mailbox empty' label
				try {
					List<?> emptyList = page
							.getByXPath("//div[@class='mailbox_empty']/h3/i");
					if (emptyList.size() != 0) {
						HtmlElement emptyElement = (HtmlElement) emptyList
								.get(0);
						customLog("Inbox empty");
					} else {
						customLog("Found a message that could not be read and it not paid message");
					}
				} catch (Exception e) {
					customException(
							"Exception in reading 'mailbox empty' label", e);
				}
				break;
			} else {
				messagesRead++;
				String messageId = anchor.getParentNode().getPreviousSibling()
						.getPreviousSibling().getFirstChild().getAttributes()
						.getNamedItem("value").getNodeValue();
				String subject = anchor.getFirstChild().getTextContent();
				String date = anchor.getParentNode().getNextSibling()
						.getTextContent();
				customLog("Message " + messagesRead + " | Id: " + messageId
						+ " | Subject: " + subject + " | Date: " + date);
				if (subject.startsWith("Survey Notification")
						|| subject.startsWith("PaidEmail - Survey")) {
					customLog("This is a survey page, deleting message");
					webClient.waitForBackgroundJavaScript(3000);
					HtmlCheckBoxInput checkbox = (HtmlCheckBoxInput) page
							.getByXPath("//input[@value='" + messageId + "']")
							.get(0);
					checkbox.click();
					page = page.getElementByName("delete").click();
					continue;
				} else {
					String advPageParams = anchor.getAttributes()
							.getNamedItem("onclick").getNodeValue();
					String advUrl = null;
					StringTokenizer stk = new StringTokenizer(advPageParams,
							",");
					if (stk.hasMoreTokens()) {
						stk.nextToken();
						advUrl = "http://www.inboxdollars.com/members/emailbox/"
								+ stk.nextToken().trim()
								+ "/"
								+ stk.nextToken().trim()
								+ "/"
								+ stk.nextToken().replace("'", "").trim();
					}
					// customLog("Formatting URL for adv page: " + advUrl);
					advPage = webClient.getPage(advUrl);
					// GeneralUtil.dumpPage(page);
					// customLog("Entering adv page");
					boolean messageSuccessfullyRead = false;

					// get confirm image link
					for (HtmlAnchor anchor1 : advPage.getAnchors()) {
						if (anchor1.getOnClickAttribute().startsWith(
								"window.open")
								|| anchor1.getOnClickAttribute().startsWith(
										"showCredited")) {
							/*
							 * HtmlElement img = (HtmlElement)
							 * anchor1.getFirstChild(); img.click();
							 */
							anchor1.click();
							Thread.sleep(5000);
							messageSuccessfullyRead = true;
							// break;
						}
					}

					if (!messageSuccessfullyRead) {
						List<?> nodes = advPage
								.getByXPath("//img[@src = 'http://www.inboxdollars.com/graphics/emails/buttons/confirmthisemailbtn.png' "
										+ "or @src = 'http://www.inboxdollars.com/graphics/site/emails/paid/advertisement/button.png' "
										+ "or @src = 'http://www.inboxdollars.com/graphics/emails/buttons/clickhereformoreinfo.png']");
						if (nodes.size() > 0) {
							HtmlImage img = (HtmlImage) nodes.get(0);
							img.click();
							Thread.sleep(5000);
							messageSuccessfullyRead = true;
							// break;
						}
					}

					// Message successfully read, delete it
					if (messageSuccessfullyRead) {
						customLog("Deleting email");
						HtmlCheckBoxInput checkbox = (HtmlCheckBoxInput) page
								.getByXPath(
										"//input[@value='" + messageId + "']")
								.get(0);
						checkbox.click();
						page.getElementByName("delete").click();
					}

					if (!messageSuccessfullyRead) {
						customLog("Message not read, cannot find appropriate link to click");
						break;
					}
				}
			}
		}

		earningAfter = checkInboxDollars();

		// logout
		customLog("Logging out: " + username);
		webClient.getPage("http://www.inboxdollars.com/members/logout/true");
		Thread.sleep(1000);
	}

	public static String checkInboxDollars() {
		HtmlPage page;
		try {
			page = webClient
					.getPage("http://www.inboxdollars.com/members/earnings");
			List<?> nodes = page
					.getByXPath("//tr[@class='summary']/td[text()='Total']");
			if (nodes != null) {
				return ((HtmlElement) nodes.get(0)).getNextSibling()
						.getTextContent();
			}
		} catch (Exception e) {
			customException("Exception in checking earnings ", e);
		}

		return null;
	}

	public static void startSendEarnings(String username, String pwd)
			throws Exception {
		HtmlPage page = null;
		HtmlPage advPage = null;

		try {
			page = webClient.getPage("http://www.sendearnings.com");
			webClient.waitForBackgroundJavaScript(5000);

			for (HtmlForm form : page.getForms()) {
				if (form.getAttribute("action").equals("/members/login")) {
					form.getInputByName("data[Member][username]")
							.setValueAttribute(username);
					form.getInputByName("data[Member][password]")
							.setValueAttribute(pwd);
					try {
						HtmlImageInput imgInput = form.getInputByName("submit");
						page = (HtmlPage) imgInput.click();
					} catch (Exception tempException) {

					}
					try {
						HtmlImageInput imgInput = form
								.getInputByName("submit2");
						page = (HtmlPage) imgInput.click();
					} catch (Exception tempException) {

					}
					break;
				}
			}
		} catch (Exception e) {
			customException("Error in logging ", e);
			return;
		}

		page = webClient.getPage("http://www.sendearnings.com/mailbox");

		webClient.waitForBackgroundJavaScript(5000);
		// customLog(page.asXml());
		try {
			earningBefore = checkSendEarnings();
		} catch (Exception e) {
			customLog("Error in checking earnings: " + e.getMessage());
		}
		customLog("Checking current earning: " + earningBefore);
		// customLog("Landed into inbox page, processing messages");
		// customLog(page.asXml());
		HtmlAnchor anchor = null;
		while (true) {

			// check if message exists
			if ((anchor = HttpUtil.getAnchorContains(page, "members/email/")) != null) {
				messagesRead++;
				String messageId = anchor.getParentNode().getPreviousSibling()
						.getPreviousSibling().getFirstChild().getAttributes()
						.getNamedItem("value").getNodeValue();
				String subject = anchor.getFirstChild().getTextContent();
				String date = anchor.getParentNode().getNextSibling()
						.getTextContent();
				customLog("Message " + messagesRead + " | Id: " + messageId
						+ " | Subject: " + subject + " | Date: " + date);

				if (subject.startsWith("Survey Notification")
						|| subject.startsWith("PaidEmail - Survey")) {
					try {
						customLog("This is a survey page, deleting message");
						webClient.waitForBackgroundJavaScript(3000);
						HtmlCheckBoxInput checkbox = (HtmlCheckBoxInput) page
								.getByXPath(
										"//input[@value='" + messageId + "']")
								.get(0);
						checkbox.click();
						page = page.getElementByName("delete").click();
					} catch (Exception e) {
						customLog(e.getMessage());
					}
					continue;
				}

				// open this email in a new window

				String advPageParams = anchor.getAttributes()
						.getNamedItem("onclick").getNodeValue();
				String advUrl = null;
				StringTokenizer stk = new StringTokenizer(advPageParams, ",");
				if (stk.hasMoreTokens()) {
					stk.nextToken();
					advUrl = "http://www.sendearnings.com/members/emailbox/"
							+ stk.nextToken().trim() + "/"
							+ stk.nextToken().trim() + "/"
							+ stk.nextToken().replace("'", "").trim();
				}
				// customLog("Formatting URL for adv page: " + advUrl);

				page = webClient.getPage(advUrl);
				// page =
				// webClient.getPage("http://www.sendearnings.com/"+anchor.getHrefAttribute());

				// GeneralUtil.dumpPage(page);
				// customLog("Entering adv page");
				// webClient.getJavaScriptEngine().pumpEventLoop(PUMP_TIME);
				webClient.waitForBackgroundJavaScript(3000);

				// different criteria for fetching adv href
				boolean messageSuccessfullyRead = false;
				for (HtmlAnchor anchor1 : page.getAnchors()) {
					if (anchor1.getHrefAttribute()
							.contains("/members/emailbox")
							|| anchor1.getHrefAttribute().contains("/mail/go")
							|| anchor1.getOnClickAttribute().startsWith(
									"window.open")) {
						anchor1.click();
						Thread.sleep(5000);
						// now delete this message
						// customLog("going to inbox to delete this message");
						page = webClient
								.getPage("http://www.sendearnings.com/mailbox");
						// webClient.getJavaScriptEngine().pumpEventLoop(PUMP_TIME);
						webClient.waitForBackgroundJavaScript(3000);
						customLog("Deleting email");
						HtmlCheckBoxInput checkbox = (HtmlCheckBoxInput) page
								.getByXPath(
										"//input[@value='" + messageId + "']")
								.get(0);
						checkbox.click();
						page = page.getElementByName("delete").click();
						messageSuccessfullyRead = true;
						break;
					}
				}

				if (!messageSuccessfullyRead) {
					customLog("Message not read, cannot find appropriate link to click");
				}
			} else {
				// check for 'mailbox empty' label
				try {
					List<?> emptyList = page
							.getByXPath("//div[@class='mailbox_empty']/h3/i");
					if (emptyList.size() != 0) {
						HtmlElement emptyElement = (HtmlElement) emptyList
								.get(0);
						customLog(emptyElement.getTextContent());
					} else {
						customLog("Found a message that could not be read and it not paid message");
					}
				} catch (Exception e) {
					customException(
							"Expecting mailbox empty message but not found", e);
				}

				break;
			}
		}

		earningAfter = checkSendEarnings();

		// logout
		customLog("Logging out: " + username);
		webClient.getPage("http://www.sendearnings.com/members/logout/true");
	}

	public static String checkSendEarnings() throws Exception {
		HtmlPage page = webClient
				.getPage("http://www.sendearnings.com/members/earnings");
		List<?> nodes = page
				.getByXPath("//tr[@class='summary']/td[text()='Total']");
		if (nodes != null) {
			return ((HtmlElement) nodes.get(0)).getNextSibling()
					.getTextContent();
		}

		return null;
	}

	public static void myPaisaLive() {
		HtmlPage page = null;
		try {
			page = webClient.getPage("http://www.paisalive.com");
			for (HtmlForm form : page.getForms()) {
				if (form.getAttribute("action").equals("/auth.asp")) {
					form.getInputByName("emailId").setValueAttribute(
							"pk.dwarka@gmail.com");
					form.getInputByName("password").setValueAttribute("pk_995");
					page = (HtmlPage) form.getInputByValue("Log in").click();
					break;
				}
			}
			// GeneralUtil.dumpPage(page);
			// webClient.getJavaScriptEngine().pumpEventLoop(PUMP_TIME);
			webClient.waitForBackgroundJavaScript(10000);
			page = (HtmlPage) webClient.getCurrentWindow().getEnclosedPage();

			// GeneralUtil.dumpPage(page);
			// check if is an intermediate advertisement page with link to
			// continue

			for (HtmlAnchor anchor : page.getAnchors()) {
				if (anchor.getHrefAttribute().startsWith("inbox.asp")) {
					customLog("Found an intermediate page; clicking on continue link");
					page = anchor.click();
					break;
				}
			}
		} catch (Exception e) {
			customException(
					"Intermediate page not found; landing directly on inbox page",
					e);
		}
		// GeneralUtil.dumpPage(page);
		try {
			customLog("Landed into inbox page, processing emails");
			HtmlAnchor anchor = null;
			while (true) {
				// check if message exists
				if ((anchor = HttpUtil.getAnchorStartsWith(page,
						"messages.asp?id=")) != null) {
					messagesRead++;
					DomNode parentNode = anchor.getParentNode().getParentNode();
					DomNodeList<DomNode> nodes = parentNode.getChildNodes();
					String from = nodes.get(0).getFirstChild().getTextContent();
					String subject = nodes.get(1).getFirstChild()
							.getFirstChild().getTextContent();
					String date = nodes.get(2).getTextContent();
					String deleteLink = nodes.get(3).getFirstChild()
							.getAttributes().getNamedItem("href")
							.getNodeValue();
					customLog("From: " + from + " | Subject: " + subject
							+ " | Date: " + date);
					// //webClient.getJavaScriptEngine().pumpEventLoop(PUMP_TIME)
					// ;
					webClient.waitForBackgroundJavaScript(3000);
					customLog("completed waiting");
					HtmlPage advPage = anchor.click();
					// GeneralUtil.dumpPage(advPage);
					customLog("entering advertisement page");
					// webClient.getJavaScriptEngine().pumpEventLoop(PUMP_TIME);
					webClient.waitForBackgroundJavaScript(5000);
					try {
						HttpUtil.getAnchorStartsWith(advPage, "details.asp")
								.click();
					} catch (Exception e) {
						customException(
								"No adv link found on this page, skipping this email",
								e);
					}

					try {
						customLog("going to inbox to delete this message");
						page = webClient
								.getPage("http://wwwp.paisalive.com/inbox.asp");
						// webClient.getJavaScriptEngine().pumpEventLoop(PUMP_TIME
						// );
						webClient.waitForBackgroundJavaScript(3000);
						customLog("Deleting email");
						page = HttpUtil.getAnchorStartsWith(page, deleteLink)
								.click();
					} catch (Exception e) {
						customException("", e);
					}
				} else {
					// no message exists, exit
					customLog("No more active messages, now checking for read messages");
					while ((anchor = HttpUtil.getAnchorContains(page,
							"delete-email.asp")) != null) {
						customLog("Deleting expired message: "
								+ anchor.getHrefAttribute());
						page = anchor.click();
						// webClient.getJavaScriptEngine().pumpEventLoop(PUMP_TIME
						// );
						webClient.waitForBackgroundJavaScript(5000);
						page = webClient
								.getPage("http://wwwp.paisalive.com/inbox.asp");
					}
					break;
				}
			}
		} catch (Exception e) {
			customException("", e);
		}
		webClient.closeAllWindows();
		customLog("Total messages read: " + messagesRead);
	}

}
